package com.nut.article.service.impl;

import com.nut.article.cache.CacheInMap;
import com.nut.article.common.Result;
import com.nut.article.entity.Tag;
import com.nut.article.mapper.TagMapper;
import com.nut.article.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private CacheInMap cacheInMap;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<Tag> list() {
        Object cache = cacheInMap.findCache(tagList, () -> {
            return tagMapper.selectList(null);
        }, 40, TimeUnit.MINUTES);

        return (List<Tag>) cache;
    }

    @Override
    public Result cleanCache() {
        cacheInMap.removeKey(tagList);
        return Result.ok();
    }

    @Override
    public Result<Tag> getById(Serializable id) {
        Tag tag = tagMapper.selectById(id);
        return Result.ok(tag);
    }

    @Override
    public Result add(Tag tag) {
        tagMapper.insert(tag);
        cacheInMap.removeKey(tagList);
        return Result.ok();
    }

    @Override
    public Result updateById(Tag tag) {
        tagMapper.updateById(tag);
        cacheInMap.removeKey(tagList);
        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        for (Integer id : ids) {
            tagMapper.deleteById(id);
        }
        cacheInMap.removeKey(tagList);
        return Result.ok();
    }
}
